package com.cn.web.app.baidu;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.config.OrderConfig;
import com.cn.exception.MyException;
import com.cn.redis.RedisHandleUtil;
import com.cn.util.Base64Util;
import com.cn.util.FileUtil;
import com.cn.util.HttpUtil3;
import com.cn.util.JsonUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.HashMap;

/**
 * description: BaiDuSdk <br>
 * date: 24.7.12 15:16 <br>
 * author: cn_yaojin <br>
 * version: 1.0 <br>
 */
@Component
@Slf4j
public class BaiDuSdk {

    @Autowired
    private OrderConfig orderConfig;

    public String getAccessTokenKey() {
        return "baidu:" + this.orderConfig.getBaidu().getClientId();
    }

    public String getAccessToken() {
        Map<String, String> pd = new HashMap<>();
        String url = "https://aip.baidubce.com/oauth/2.0/token?client_id=" + orderConfig.getBaidu().getClientId() + "&client_secret=" + orderConfig.getBaidu().getClientSecret() + "&grant_type=client_credentials";
        String result = HttpUtil3.doPost(url, JsonUtil.toJson(pd));

        AccessTokoenResp resp = JSON.parseObject(result, AccessTokoenResp.class);
        if (StringUtils.isNotEmpty(resp.getAccess_token())) {
            RedisHandleUtil.add(getAccessTokenKey(), resp.getAccess_token(), resp.getExpires_in());
            return resp.getAccess_token();
        } else {
            log.error("获取百度accessToken失败：{}", resp.getError());
        }
        return null;
    }

    /**
     * 获取accessToken
     *
     * @return
     */
    public String getAccessTokenCache() {
        String value = RedisHandleUtil.get(getAccessTokenKey());
        if (StringUtils.isNotEmpty(value)) {
            return value;
        }
        return getAccessToken();
    }

    public Object iocrRecognise(String templateId, String fileBase64) {
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise?access_token=" + getAccessTokenCache();
        Map<String, Object> pd = new HashMap<>();
        pd.put("templateSign", templateId);
        pd.put("image", fileBase64);
        String result = HttpUtil.post(url, pd);
        JSONObject json = JSON.parseObject(result);
        int error_code = json.getInteger("error_code");
        String error_msg = json.getString("error_msg");
        if (error_code == 0) {
            return json.get("data");
        } else {
            throw new MyException("识别失败：" + error_msg);
        }
    }

    @Setter
    @Getter
    @Accessors(chain = true)
    public static class AccessTokoenResp {

        private String error;

        private String error_description;

        private String access_token;

        private long expires_in;

    }


}
